﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using DataLoader.Common.Config;
using DataLoader.Config;

namespace DataLoader.UI.Models
{
    public class MainModelService
    {
        public string ConnString { get; private set; }

        public MainModelService(string connString)
        {
            ConnString = connString;
        }

        public IAsyncResult BeginFetchConfigItems(object input, AsyncCallback ac, object state)
        {
            Task<List<IConfigItem>> f = Task<List<IConfigItem>>.Factory.StartNew((s) => FetchConfigItems(), state, TaskCreationOptions.None);
            if (ac != null)
            {
                f.ContinueWith((res) => ac(f))
                 .ContinueWith((Task previous) => { var e = previous.Exception; throw e; }, TaskContinuationOptions.OnlyOnFaulted);
            }
            return f;
        }


        public List<IConfigItem> EndFetchConfigItems(IAsyncResult ar)
        {
            if (((Task<List<IConfigItem>>)ar).IsFaulted)
            {
                return null;
            }
            return ((Task<List<IConfigItem>>)ar).Result;
        }


        public List<IConfigItem> FetchConfigItems()
        {
            ConfigFetcher configFetcher = new ConfigFetcher() { ConnString = ConnString };
            List<IConfigItem> configItems = new List<IConfigItem>
                                                            (
                                                                configFetcher.GetItemsToLoad()
                                                                             .Select
                                                                             (
                                                                                 p => new ConfigItem()
                                                                                 {
                                                                                     IsEnabled = p.IsEnabled,
                                                                                     SourceSystem = p.SourceSystem,
                                                                                     Source = p.Source.Substring(p.Source.LastIndexOf(@"\") + 1),
                                                                                     Destination = p.Destination,
                                                                                     IsDirty = false                                                                                     
                                                                                 }
                                                                             )
                                                            );
            return configItems;
        }
    }
}
